<?php
/**
 * ShopEx licence
 *
 * @copyright  Copyright (c) 2005-2010 ShopEx Technologies Inc. (http://www.shopex.cn)
 * @license  http://ecos.shopex.cn/ ShopEx License
 */

/**
 * 单商品减固定价格购买
 * $ 2010-05-04 16:51 $
 aaa
 */
class gift_promotion_solutions_gift implements b2c_interface_promotion_solution
{
    public $name = "送赠品(满赠促销)"; // 名称
    public $type = 'goods'; //默认goods
    public $desc_pre = '获得赠品';
    public $desc_post = '';
    public $score_add = true;
    public $desc_tag = '送赠品';
    public $cart_display = false;//对应的商品优惠是否在购物车中显示

    //开启此项时。此优惠也会应用到商品以外。如购物车中只有礼包
    public $actiontoall = true;

    private $description = '';




    /**
     * 优惠方案模板
     * @param array $aConfig // 设置信息(修改的时候传入)
     * @return string // 返回要输出的模板html
     */
    public function config($aData = array()) {
       // var_dump($aData);
        $render = app::get('gift')->render();
        $render->pagedata['value'] = $aData['gain_gift'];
        $render->pagedata['object'] = 'goods';
        $render->pagedata['name'] = 'action_solution[gift_promotion_solutions_gift][gain_gift]';

        //这里要访问数量
        
       // var_dump()
        return $this->desc_pre . $render->fetch('admin/sales/dialog.html');  
        //app/D:\WWW\Nnew_ecstore24\app\gift\view\admin\sales
    }


    //@mo
    //返回当前购物车中该商品的索引
    
    public function get_good_id_from_cart($cart_object_goods=array(),$goods_id)
    {
        if(count($cart_object_goods) == 0)
            return -1;
        foreach ($cart_object_goods as $key => $value) {
            if($value['params']['goods_id'] == $goods_id )
            {
                return $key;
            }
        }
        return -1;
    }
     public function get_number_from_rule_in_order($rule_protion)
    {		
//    	  echo '<pre>';
//         echo '----ggg--uu-111------<br>';

           $member_id = kernel::single('b2c_user_object')->get_member_id();
//         var_dump($rule_protion);
//         echo '----ggg--uu-222------<br>';
            
            $db_order = app::get('b2c')->model('orders');

             $fromtime = $rule_protion['from_time'];
             $totime = $rule_protion['to_time'];

             $filter = array('member_id'=>$member_id,'createtime|bthan'=>$fromtime,'createtime|sthan'=>$totime,'status|noequal'=>'dead');//modify by hzk 05-26 排除废单 status = dead
//         var_dump($filter);
//         echo '----ggg--uu-111------<br>';
       
           //根据当前的促销条件到订单中心去获取当前这个人已经购买的数量
            $this_member_all_orders = $db_order->getList('order_id,member_id,createtime', $filter, 0, -1, 'order_id ASC');
//		echo '<pre>';
//         var_dump($this_member_all_orders);
//         echo '----ggg--uu-111------<br>';
  
            $db_order_goods = app::get('b2c')->model('order_items');
            $gift_type = app::get('b2c')->_('product');
            //促发条件的 个数 $rule_protion['conditions']['conditions'][0]['value']
            
            $order_goods_nums = 0;//当前用户之前购买的数量
            foreach ($this_member_all_orders as $one_order) {
                $temp_filter = array('order_id'=>$one_order,'item_type|nequal'=>$gift_type,'goods_id'=>$rule_protion['conditions']['conditions'][0]['conditions'][0]['value']);
                $temp_goods = $db_order_goods->getList('goods_id,name,nums,order_id', $temp_filter, 0, -1, 'order_id ASC');

                if(!empty($temp_goods) && (int)$temp_goods[0]['nums'] >= $rule_protion['conditions']['conditions'][0]['value'])
                {
                    $order_goods_nums += (int)$temp_goods[0]['nums'];//总计订单中该商品的个数
                    
                }
            }
//			echo '<pre>';
//  			var_dump($order_goods_nums);

            return  $order_goods_nums;
    }
    
    /**
     * 优惠方案应用
     *
     * @param array $object  // 引用的一个商品信息
     * @param array $aConfig // 优惠的设置
     * @param array $cart_object // 购物车信息(预过滤的时候这个为null)
     * @return void // 引用处理了,没有返回值
     */
    //@mo minicart 购物 ，下单都有影响
    public function apply(&$object,$aConfig,$rule,&$cart_object = null) {

//         echo '<pre>'; 
        // var_dump($rule);
//         echo '----ggg-00------';
        $t = $arr = $this->__process( $aConfig );
        
        //促销的规则
         $rule_id = $arr[0]['rule_id'][0];
        //@mo 
        //__process里根据促销规则获取赠品的数量,
        //这里再根据购物车单品的数量来设置具体赠品个数
        $mNumber = app::get('b2c')->model('sales_rule_order');
            $filter = array('rule_id'=>$rule_id);
            $gift_number_arr = $mNumber->getList('rule_id,gift_number,conditions,from_time,to_time', $filter, 0, -1, 'rule_id ASC');

        //$arr[0]['quantity']
        //规则满多少送多少个赠品
        $rule_id_gift_number = $gift_number_arr[0]['conditions']['conditions'][0]['value'];
        //封顶数
        $rule_id_goods_maxnum = $gift_number_arr[0]['conditions']['conditions'][0]['maxquantity'];
		//订单中的商品个数        
        $goods_in_order = $this->get_number_from_rule_in_order($gift_number_arr[0]);
//          echo '<pre>';
//         var_dump($gift_number_arr[0]['conditions']['conditions'][0]);
//         echo '----ggg--uu-------<br>';
//         var_dump($goods_in_order);
//         echo '----ggg--uu-------<br>';
        //目前该商品的个数
       // $order_present_number = $cart_object['object']['goods'][0]['quantity'];
        //要确定所选择的商品与该促销条件商品符合
        
        //从促销条件中获取该商品名id
        $present_good_id = $gift_number_arr[0]['conditions']['conditions'][0]['conditions'][0]['value'];
        //根据商品id_到目前购物车中对应商品的数量
       $goods_index = $this->get_good_id_from_cart($cart_object['object']['goods'],$present_good_id);
        //目前该商品的个数
        $order_present_number = $cart_object['object']['goods'][$goods_index]['quantity'];
        //$order_present_number = 0;
        //最后需要赠送的个数
        if($order_present_number < $rule_id_gift_number){
             $final_need_gift_number = 0;
//         echo '----ggg-11------';
         }
        else
        {
            //取整乘上赠品倍数
             $multiple_gift = intval(floor($order_present_number/$rule_id_gift_number));
             $final_need_gift_number = $multiple_gift *$gift_number_arr[0]['gift_number'];
          
//         echo '----ggg-22------';
//         var_dump($order_present_number);
//         var_dump($gift_number_arr[0]['gift_number']);
//         var_dump($final_need_gift_number);
				//封顶数
             	$final_need_gift_maxnumber = intval(floor($rule_id_goods_maxnum/$rule_id_gift_number))*$gift_number_arr[0]['gift_number'];
             	//订单内
             	$goods_in_order_gift_num = intval(floor($goods_in_order/$rule_id_gift_number))*$gift_number_arr[0]['gift_number'];
             	
             
             	
             if(($order_present_number + $goods_in_order) > $rule_id_goods_maxnum){
             	//已经购买大于封顶值
             	if($goods_in_order > $rule_id_goods_maxnum || $goods_in_order > ($rule_id_goods_maxnum - $rule_id_gift_number) ){
             		//$goods_in_order_gift_num = $final_need_gift_maxnumber;
             		$final_need_gift_number = 0;
             		
             	}else{
             		//未达到封顶值
             		$final_need_gift_number = intval(floor(($rule_id_goods_maxnum-$goods_in_order)/$rule_id_gift_number))*$gift_number_arr[0]['gift_number'];
             	}
             	
             	
//             	         echo '=======<br>';
//         var_dump($order_present_number);
//             	         echo '=======<br>';
//         var_dump($goods_in_order_gift_num);
//             	         echo '=======<br>';
//         var_dump($final_need_gift_maxnumber);
             	
             }        
        }
        $t[0]['quantity'] = $arr[0]['quantity'] = $final_need_gift_number;
      
//         echo '----ggg--uu--444-----<br>';
//         var_dump($final_need_gift_number);
      
          //echo '<pre>';
        //var_dump($gift_number_arr[0]['gift_number']);//can show
        //var_dump($t[0]['quantity']);//can show
        /*echo "rule_id:".$rule_id.'<br>';
         echo '---------------<br>';
         echo "rule_id_gift_number:".$rule_id_gift_number.'<br>';
         echo '---------------<br>';
         echo "present_good_id:".$present_good_id.'<br>';
         echo '---------------<br>';
         echo "goods_index:".$goods_index.'<br>';
         echo '---------------<br>';
         echo "order_present_number:".$order_present_number.'<br>';
         echo '---------------<br>';
         echo "final_need_gift_number:".$final_need_gift_number.'<br>';
         echo '---------------<br>';
         
         echo '------TTTTTTTTTT---------<br>';
        */
        if( !$arr ) return false;

        if( is_null($cart_object) || empty($cart_object) ) { // 商品预过滤
            $this->desc_pre = app::get('gift')->_('商品获得赠品');
            if( is_array( $object['gift'] ) ) {
                foreach( $object['gift'] as $_k => &$_v ) {
                    foreach( (array)$arr as $_key => $val ) {
                        if( $val['product_id']==$_v['product_id'] ) {
                            unset($arr[$_key]);
                            $_v['quantity'] += $val['quantity'];
                            $_v['rule_id'] = array_merge( (array)$_v['rule_id'],(array)$val['rule_id'] );
                        }
                    }
                }
            }
            $object['gift'] = array_merge((array)$object['gift'],$arr);
        } else {// 购物车里的处理
            $this->desc_pre = app::get('gift')->_('获得赠品');
            if( is_array( $cart_object['object']['gift']['order'] ) ) {
                foreach( $cart_object['object']['gift']['order'] as $_k => &$_v ) {
                    foreach( (array)$arr as $_key => $val ) {
                        if( $val['product_id']==$_v['product_id'] ) {
                            unset($arr[$_key]);
                            $_v['quantity'] += $val['quantity'];
                            $_v['rule_id'] = array_merge( (array)$_v['rule_id'],(array)$val['rule_id'] );
                        }
                    }
                }
            }
            $cart_object['object']['gift']['order'] = array_merge((array)$cart_object['object']['gift']['order'],$arr);
        }
        $this->setString($t);

    }




    /**
     * 优惠方案应用
     *
     * @param array $object  // 引用的一个商品信息
     * @param array $aConfig // 优惠的设置
     * @param array $cart_object // 购物车信息(预过滤的时候这个为null)
     * @return void // 引用处理了,没有返回值
     */
    public function apply_order(&$object, &$aConfig,$rule,&$cart_object = null) {
            // echo '<pre>';
            //     var_dump($rule);
            //     echo 'pppppppppppppp';
        if(is_null($cart_object)) return false;

        $t = $arr = $this->__process( $aConfig );
        //echo '<pre>';
        //var_dump($arr);//no show
        if( !$arr ) return false;
        //送赠品 如果该赠品已存在则累加
        if( is_array( $cart_object['object']['gift']['order'] ) ) {
            foreach( $cart_object['object']['gift']['order'] as $_k => &$_v ) {
                foreach( (array)$arr as $_key => $val ) {
                    if( $val['product_id']==$_v['product_id'] ) {
                        unset($arr[$_key]);
                        $_v['quantity'] += $val['quantity'];
                        //$_v['quantity'] += 2;
                        $_v['rule_id'] = array_merge( (array)$_v['rule_id'],(array)$val['rule_id'] );
                    }
                }
            }
        }
        $cart_object['object']['gift']['order'] = array_merge((array)$cart_object['object']['gift']['order'],$arr);


        $this->desc_pre = app::get('gift')->_('订单获得赠品');
        $this->setString($t);
    }


    private function __process( &$aConfig ) {
    
        //echo '<pre>';
        //var_dump($this->rule_id);//no show
        //echo '------AA---------<br>';
        if(!isset($aConfig['gain_gift']) || empty($aConfig['gain_gift'])) return false;
        $arr = kernel::single("gift_cart_object_goods")->_get_products($aConfig['gain_gift']);
        foreach( $aConfig['gain_gift'] as $_gift_id ) {
            if( !$arr[$_gift_id] ) codntinue;
            $t = $arr[$_gift_id];
            if( !($t['store']-$t['freez']) || !$t['_limit'] ) continue;
            $arr[$_gift_id]['rule_id'][] = $this->rule_id;
			//$arr[$_gift_id]['quantity'] = 4;//can influence
			//这里根据规则查询促销中的giftnumber//@mo
			$mNumber = app::get('b2c')->model('sales_rule_order');
			$filter = array('rule_id'=>$arr[$_gift_id]['rule_id'][0]);
			$gift_number_arr = $mNumber->getList('rule_id,gift_number', $filter, 0, -1, 'rule_id ASC');
			$arr[$_gift_id]['quantity'] = $gift_number_arr[0]['gift_number'];

            $tmp[] = $arr[$_gift_id];
        }
        $this->rule_id = null;
		
		
        return $tmp;
        #$cart_object['object']['gift']['order'] = array_merge( (array)$cart_object['object']['gift']['order'], $arr );
    }


    public function setString($aData) {
        if( ($tmp=$this->__process($aData)) ) {
            $aData = $tmp;
        }

        //
        //echo '<pre>';
        //var_dump($aData);
        if( is_array($aData) ) {
            $a = array();
            foreach( $aData as $row ) {
                if( !is_array($row) || !$row['name'] ) continue;
                $a[] = '<a href="'. app::get('site')->router()->gen_url( array('app'=>'gift','act'=>'index','ctl'=>'site_gift','arg0'=>$row['goods_id']) ) .'" target="_gift_blank">'.$row['name'].'</a>';
            }

            if( $a && is_array($a) )
                $str = implode('<br />', $a);
        }

        if( $str )
            $this->description = $this->desc_pre . $str;
        else
            $this->description = '';
    }

    public function getString($aData=array()) {
        return $this->description;
    }

    public function get_status() {
        return true;
    }

	/**
	 * 校验参数是否正确
	 * @param mixed 需要校验的参数
	 * @param string error message
	 * @return boolean 是否成功
	 */
	public function verify_form($data=array(), &$msg='')
	{
		if (!$data) return true;

		/** 订单够满金额 **/
		if (!isset($data['action_solution']['gift_promotion_solutions_gift']['gain_gift']) || !$data['action_solution']['gift_promotion_solutions_gift']['gain_gift'])
		{
			$msg = app::get('b2c')->_('请指定需要赠送的赠品！');
			return false;
		}
		/** end **/

		return true;
	}

    function get_desc_tag(){
        if(isset($this->cart_display)){
            $desc_tag['display'] = $this->cart_display;
        }else{
            $desc_tag['display'] = true;
        }
        $desc_tag['name'] = $this->desc_tag;
        return $desc_tag;
    }
}

